package main

import (
	"AntLinkerIMServerMonitor/control"
	"antServer/antPublic"
	"antServer/slog"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/antlinker/asapi"
	"github.com/codegangsta/cli"
)

var done = make(chan int)

func createFlags() []cli.Flag {
	return []cli.Flag{
		cli.StringFlag{
			Name:  "config, c",
			Value: "./conf/config.yaml",
			Usage: "服务配置文件",
		},
		cli.StringFlag{
			Name:  "log, l",
			Value: "./conf/log.yaml",
			Usage: "日志配置文件",
		},
	}
}

var Debug = false

func createPassword() string {
	token, err := asapi.ForceGetToken()
	if err != nil {
		//ALOG.Warn("获取令牌失败:(%d):%s", err.Code, err.Message)
	}
	return "SERVER_" + token
}
func createAction(ctx *cli.Context) {
	slog.SlogInit(ctx.String("log"), "AntServerMonitor")

	control.TlogInit(ctx.String("log"))
	config := control.CreateConfig(ctx.String("config"))

	server := http.Server{
		Addr: config.ServerAddr,
		//Handler:     &MyHandle{},
		ReadTimeout: 6 * time.Second,
	}
	if config.Mongodb.URL == "" {
		control.Tlog.Error("未配置mongodb数据库连接")
		os.Exit(0)
	}
	control.Tlog.Debug("创建数据库连接")
	control.CreateMyMgo(config.Mongodb)
	control.Tlog.Debug("开启服务")
	// 初始化认证服务
	asapi.InitAPI(&asapi.Config{
		ASURL:           config.Authorize.URL,
		ClientID:        config.Authorize.ClientID,
		ClientSecret:    config.Authorize.ClientSecret,
		ServiceIdentify: config.Authorize.Identify,
		IsEnabledCache:  true,
		CacheGCInterval: 60,
	})

	options := &antPublic.MqttOption{
		BrokerAddress:     config.MqttClient.BrokerAddress,
		Timeout:           uint16(config.MqttClient.Keepalive),
		CachePath:         config.CachePath,
		FileName:          "aaaa",
		ReconnectInterval: int(config.MqttClient.ReconnectInterval),
		Username:          "SA_" + config.Authorize.ClientID,
		PasswordHandler:   createPassword,
	}
	antPublic.IntMqttOption("aaaa", "SB", options)

	//public.PutAuthKey(options.Username, webkey, options.Password)

	antPublic.StartMqtt(options)
	// //建立mqtt连接
	// option := &antPublic.MqttOption{
	// 	BrokerAddress:     config.MqttClient.BrokerAddress,
	// 	Timeout:           config.MqttClient.Keepalive * time.Second,
	// 	AutoReconnect:     true,
	// 	CachePath:         config.CachePath,
	// 	FileName:          config.MqttClient.ClientIdFileName,
	// 	ReconnectInterval: config.MqttClient.ReconnectInterval * time.Second,
	// }

	// antPublic.IntMqttOption(config.MqttClient.ClientIdPrefix, "SB", option)
	// antPublic.StartMqtt(option)

	err := server.ListenAndServe()

	if err != nil {
		log.Fatal(err)
	}
	time.Sleep(time.Second)
	/*
	   让程序一直运行下去，一直到接收到退出指令，done通道收到0后5秒钟退出
	*/
	if i := <-done; i == 0 {
		slog.Slog.Debug("##收到程序退出指令，程序将在5秒后退出")
		time.Sleep(5 * time.Second)
		//unsubSystemTopics(c)
		//antPublic.GetMqttClientForConsole().Disconnect(250)
		//c.Disconnect(250)
		slog.Slog.Debug("##已成功断开连接")
		os.Exit(0)
	}
	slog.Slog.Debug("主进程结束")

}
func main() {
	app := cli.NewApp()
	app.Name = "集结号App测试服务-http"
	app.Author = "@antlinker.com"
	app.Version = "0.1.0"
	app.Usage = "集结号App测试-http"
	app.Flags = createFlags()
	app.Action = createAction

	//app.Commands = append(app.Commands, createAppServer())
	app.Run(os.Args)
}
